﻿using System;
using System.Drawing;
using System.Web.Security;
using ELearningSystem.Gateway.Entities;
using UserManager = ELearningSystem.UI.LearnerServiceReference.LearnerServiceSoapClient;
using Learner = ELearningSystem.UI.LearnerServiceReference.LearnerDAO;

namespace ELearningSystem.UI.UserUI
{
    public partial class UserLoginUI : System.Web.UI.Page
    {
        UserManager userManager = new UserManager();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                signUpErrorMessage.ForeColor = Color.Green;
                signUpErrorMessage.Text = Request.QueryString["SignUpMessage"];
            }
        }

        protected void signInButton_Click(object sender, EventArgs e)
        {
            Response.Cache.SetNoStore();
            FormsAuthentication.SignOut();

            Learner anLearner = new Learner();
            anLearner.EmailAddress = loginEmailTextBox.Text;
            anLearner.Password = loginPasswordTextBox.Text;
            Learner authenticatedLearner = new Learner();
            UserManager userManager = new UserManager();
            if (userManager.IsAuthenticatedUser(anLearner,out authenticatedLearner))
            {
                FormsAuthentication.RedirectFromLoginPage(authenticatedLearner.Name,true);
            }
            if (userManager.IsAdmin(anLearner))
            {
                
                Response.Redirect("~/AdminUI/AdminHomePageUI.aspx");
            }

        }

        protected void submitLinkButton_Click(object sender, EventArgs e)
        {
            try
            {
                Learner learner = new Learner();
                learner.Name = nameTextBox.Text;
                learner.EmailAddress = emailTextBox.Text;
                learner.Password = passwordTextBox.Text;
                string message = userManager.SaveOrUpdateLearner(learner);
                Response.Redirect("~/UserUI/UserLoginUI.aspx?SignUpMessage="+message);
                
            }
            catch (Exception exception)
            {

                signUpErrorMessage.ForeColor = Color.Red;
                signUpErrorMessage.Text = exception.Message;
            }
            
        }
    }
}